//
//  GameScene.cpp
//  kasama1
//
//  Created by 丁逸鹏 on 15/3/3.
//
//


#include "GameScene.h"
Scene * GameScene::createScene()
{
    auto scene = Scene :: create();
    auto layer= GameScene::create();
    scene->addChild(layer);
    return scene;
    
}
bool GameScene::init()
{
    if(!Layer::init())
    {
        return false;
    }
    isbegin=false;
    srand(time(NULL));
    score=global->score;
    remain=global->remainoperate;
    UserDefault::getInstance()->setIntegerForKey("name",333);
    isRun=false;
    Sprite *background =Sprite::create("images/Background/bg_iphone.png");
    background->setAnchorPoint(Vec2(0,0));
    background->setScale(0.7);
    addChild(background,-2);
    char mapname[20];
    sprintf(mapname,"maps/%d.tmx",global->mapid);
    map=TMXTiledMap::create(mapname);
    map->setAnchorPoint(Vec2(0.5,0.5));
    map->setPosition(VisibleRect::center());
    map->setScale(0.5);
    addChild(map);
    layer=map->getLayer("mainlayer");
    entitylist=new Entity**[MAX_HEIGHT];
    for(int i=0;i<MAX_HEIGHT;i++)
    {
        entitylist[i]=new Entity*[MAX_WIDTH];
    }
    
    auto ui=cocostudio::GUIReader::getInstance()->widgetFromJsonFile("GameScene/GameScene.ExportJson");
    addChild(ui,-1);
    Button * pause = (Button*)Helper::seekWidgetByName(ui,"Button_Pause");
    pause->addTouchEventListener(this,toucheventselector(GameScene::pauseDialogCallBack));
    Button * down = (Button*)Helper::seekWidgetByName(ui,"Button_down");
    down->addTouchEventListener(this,toucheventselector(GameScene::downPartriesCallBack));
    
    pauseDialog=cocostudio::GUIReader::getInstance()->widgetFromJsonFile("pauseDialog/pauseDialog.ExportJson");
    pauseDialog->retain();
    addChild(pauseDialog,2);
    pauseDialog->setVisible(false);
    Button *playresumeButton=(Button*)Helper::seekWidgetByName(pauseDialog,"Button_play");
    playresumeButton->addTouchEventListener(this,toucheventselector(GameScene::playCallBack));
    Button * backtomenu=(Button*)Helper::seekWidgetByName(pauseDialog,"Button_quit");
    backtomenu->addTouchEventListener(this,toucheventselector(GameScene::BacktoHome));
    CheckBox * checkBox=(CheckBox*)Helper::seekWidgetByName(pauseDialog,"CheckBox");
    checkBox->setSelectedState(global->isPlayMusic);
    checkBox->addEventListenerCheckBox (this,checkboxselectedeventselector(GameScene::changeMusicState));
    Slider * slidevolume=(Slider*)Helper::seekWidgetByName(pauseDialog,"Slider");
    slidevolume->setPercent(global->volume);
    slidevolume->addEventListenerSlider(this,sliderpercentchangedselector(GameScene::sliderchangecallBack));
    
    
    startDialog=cocostudio::GUIReader::getInstance()->widgetFromJsonFile("startdialog/startdialog.ExportJson");
    startDialog->setAnchorPoint(Vec2(0.5,0.5));
    startDialog->setPosition(VisibleRect::center());
    startDialog->setScale(1.2);
    addChild(startDialog,2);
    
    
    Button *closeButton=(Button*)Helper::seekWidgetByName(startDialog,"CloseButton");
    Button *playButton=(Button*)Helper::seekWidgetByName(startDialog,"PlayButton");
    closeButton->addTouchEventListener(this,toucheventselector(GameScene::startGame));
    playButton->addTouchEventListener(this,toucheventselector(GameScene::startGame));
    
    //windialog
    winDialog=cocostudio::GUIReader::getInstance()->widgetFromJsonFile("pass/pass.ExportJson");
    winDialog->setAnchorPoint(Vec2(0.5,0.5));
    winDialog->setPosition(Vec2(VisibleRect::top().x,VisibleRect::top().y+600));
    addChild(winDialog,2);
    Button *continueButton=(Button*)Helper::seekWidgetByName(winDialog,"Button_continue");
    Button *homeButton=(Button*)Helper::seekWidgetByName(winDialog,"Button_home");
    continueButton->addTouchEventListener(this,toucheventselector(GameScene::continueGame));
    homeButton->addTouchEventListener(this,toucheventselector(GameScene::BacktoHome));
    
    
    falseDialog =cocostudio::GUIReader::getInstance()->widgetFromJsonFile("fail/fail.ExportJson");
    falseDialog->setAnchorPoint(Vec2(0.5,0.5));
    falseDialog->setPosition(Vec2(VisibleRect::top().x,VisibleRect::top().y+600));
    addChild(falseDialog,2);
    
    Button *homeButton2=(Button*)Helper::seekWidgetByName(falseDialog,"Button_home");
    
    homeButton2->addTouchEventListener(this,toucheventselector(GameScene::BacktoHome));
    goalnodelist=new GoalNode*[global->needpatriesnum];
    switch (global->goalindex)
    {
        case 0:
            for(int i=0;i<global->needpatriesnum;i++)
            {
                CCLOG("init patries %d",i);
                goalnodelist[i]=new GoalNode(i);
                goalnodelist[i]->setPosition(Vec2(VisibleRect::center().x-(global->needpatriesnum-1)*25+i*50,
                                                  VisibleRect::center().y+50));
                addChild(goalnodelist[i],3);
            }
            break;
        default:
            break;
    }
    scoresprite=Sprite::create("images/score.png");
    scoresprite->setPosition(Vec2(VisibleRect::leftBottom().x+20,VisibleRect::leftBottom().y+20));
    scoresprite->setScale(0.5);
    scoresprite->setAnchorPoint(Vec2(0,0));
    addChild(scoresprite,2);
    scoreLabel=LabelAtlas::create("0123456789", "shu2.png",26,31,'0');
    scoreLabel->setScale(0.5);
    scoreLabel->setPosition(Vec2(VisibleRect::leftBottom().x+scoresprite->getContentSize().width/2+30,
                                 VisibleRect::leftBottom().y+20));
    addChild(scoreLabel,2);
    char scorestr[10];
    sprintf(scorestr,"%d",global->score);
    scoreLabel->setString(scorestr);
    
    // £”‡≤Ω ˝
    remainLabel=LabelAtlas::create("0123456789", "shu2.png",26,31,'0');
    remainLabel->setAnchorPoint(Vec2(0.5,0));
    remainLabel->setScale(0.5);
    remainLabel->setPosition(Vec2(305,VisibleRect::rightBottom().y+20));
    addChild(remainLabel);
    char remainnum[10];
    sprintf(remainnum,"%d",global->remainoperate);
    remainLabel->setString(remainnum);
    auto listener = EventListenerKeyboard::create();
    listener->onKeyReleased = CC_CALLBACK_2(GameScene::keyBackClicked,this);
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this);
    
    
    return true;
}
Point GameScene::tileCoordForPosition(Point pos)
{
    int posxstart=map->getPositionX()-map->getContentSize().width/2/2;
    int posystart=map->getPositionY()-map->getContentSize().height/2/2;
    
    int posx=(pos.x+0.5)*map->getTileSize().width/2+posxstart;
    int posy=(pos.y+0.5)*map->getTileSize().height/2+posystart;
    return Point(posx,posy);
}
void GameScene::updategame(float dt)
{
    /*if(!entities.empty())
     {
     for(auto &entity:entities)
     {
     Entity *node =dynamic_cast<Entity*>(entity);
     this->removeChild(node);
     }
     }*/
    //this->removeChildByTag(1);
    if(m_isAnimationing)
    {
        m_isAnimationing=false;
        //	CCLOG("ssss");
        for(int i=0;i<MAX_HEIGHT;i++)
        {
            for(int j=0;j<MAX_WIDTH;j++)
            {
                //entitylist[i][j]->runAction(JumpBy::create(1,Vec2(0,0),100,1));
                //if(NULL==entitylist[i][j]){
                //	//m_isAnimationing=true;
                //	continue;
                //}
                int tileid=layer->getTileGIDAt(Vec2(i,j));
                if(tileid!=0){
                    Entity * entity=entitylist[i][j];
                    if(NULL==entity)
                    {
                        continue;
                    }
                    if(entity &&entity->getNumberOfRunningActions()>0)
                    {
                        
                        m_isAnimationing=true;
                        break;
                    }
                }
                
            }
        }
    }
    if(!m_isAnimationing)
    {
        
        CheckAndRemove();
    }
    //CheckAndRemove();
    
    //this->remo
}
void GameScene::CreateAndDrop(int row,int col)
{
    Entity * node=new Entity();
    node->retain();
    entitylist[row][col]=node;
    node->setRow(row);
    node->setCol(col);
    node->setIsInfty(false);
    node->setPosition(tileCoordForPosition(Vec2(col,row+10)));
    node->setIsNeedRemove(false);
    addChild(node);
    node->stopAllActions();
    node->runAction( MoveTo::create(2,Vec2(tileCoordForPosition(Vec2(col,row)))));
    m_isAnimationing=true;
    //	CCLOG("%d,%d",row,col);
    
}
void GameScene::CheckAndRemove()
{
    //∫·œÚºÏ≤‚
    
    std::list<Entity *> removeList;
    for(int i=0;i<MAX_HEIGHT;i++)
    {
        for(int j=0;j<MAX_WIDTH;j++)
        {
            Entity * node=entitylist[i][j];
            if(NULL== node||node->getIsInfty()){
                continue;
            }
            std::list<Entity *> rowchainList;
            getColChain(node,rowchainList);
            std::list <Entity *> colchainList;
            getRowChain(node,colchainList);
            //	CCLOG("%d",colchainList.size());
            if((colchainList.size()>=3||rowchainList.size()>=3)){
                
                //Àƒœ˚«Èøˆ
                if(colchainList.size()>=4)
                {
                    std::list<Entity*>::iterator itr= colchainList.begin();
                    int flag=0;
                    for(;itr!=colchainList.end();itr++)
                    {
                        Entity * node =*itr;
                        if(node->getNowState()==Entity::rowcrush){
                            flag=1;
                            break;
                        }
                        
                        
                    }
                    if(flag==0)
                    {
                        entitylist[i][j]->changeState(Entity::rowcrush);
                    }
                    if(entitylist[i][j]->getNowState()!=Entity::rowcrush)
                    {
                        markRemove(node);
                    }
                }
                else if(rowchainList.size()>=4){
                    std::list<Entity*>::iterator itr= rowchainList.begin();
                    int flag=0;
                    for(;itr!=rowchainList.end();itr++)
                    {
                        Entity * node =*itr;
                        if(node->getNowState()==Entity::colcrush){
                            flag=1;
                            break;
                        }
                        
                        
                    }
                    if(flag==0)
                    {
                        entitylist[i][j]->changeState(Entity::colcrush);
                    }
                    if(entitylist[i][j]->getNowState()!=Entity::colcrush)
                    {
                        markRemove(node);
                    }
                }
                else if(colchainList.size()==3&&rowchainList.size()==3)
                {
                    
                    entitylist[i][j]->changeState(Entity::boss);
                    
                }
                else{
                    //∆’Õ®»˝œ˚
                    markRemove(entitylist[i][j]);
                }
            }
            
        }
    }
    for(int i=0;i<MAX_HEIGHT;i++)
    {
        for(int j=0;j<MAX_WIDTH;j++)
        {
            Entity * node = entitylist[i][j];
            if(node&&node->getIsNeedRemove())
            {
                this->removeChild(node);
                explode(node->getPosition());
                entitylist[i][j]=NULL;
            }
        }
    }
    fillPosition();
    
    //◊›œÚºÏ≤‚
}
void GameScene ::getColChain(Entity * node,std::list<Entity *>& chainList)
{
    chainList.push_back(node);
    //CCLOG("%d",chainList.size());
    int neighborCol=node->getCol()-1;
    while(neighborCol>=0)
    {
        Entity * entity = entitylist[node->getRow()][neighborCol];
        if(NULL==entity||entity->getIsInfty())
        {
            break;
        }
        if(entity->getTag()==node->getTag())
        {
            chainList.push_back(entity);
            neighborCol--;
        }
        else
        {
            break;
        }
        
    }
    neighborCol=node->getCol()+1;
    while(neighborCol<MAX_WIDTH)
    {
        Entity * entity = entitylist[node->getRow()][neighborCol];
        if(NULL==entity||entity->getIsInfty())
        {
            break;
        }
        if(entity->getTag()==node->getTag())
        {
            chainList.push_back(entity);
            neighborCol++;
        }
        else
        {
            break;
        }
    }
    
}
void GameScene ::getRowChain(Entity * node,std::list<Entity *>& chainList)
{
    chainList.push_back(node);
    int neighborRow=node->getRow()-1;
    while(neighborRow>=0)
    {
        Entity * entity = entitylist[neighborRow][node->getCol()];
        if(NULL==entity||entity->getIsInfty())
        {
            break;
        }
        if(entity->getTag()==node->getTag())
        {
            chainList.push_back(entity);
            neighborRow--;
        }
        else
        {
            break;
        }
        
    }
    neighborRow=node->getRow()+1;
    while(neighborRow<MAX_HEIGHT)
    {
        Entity * entity = entitylist[neighborRow][node->getCol()];
        if(NULL==entity||entity->getIsInfty())
        {
            break;
        }
        if(entity->getTag()==node->getTag())
        {
            chainList.push_back(entity);
            neighborRow++;
        }
        else
        {
            break;
        }
    }
}
void GameScene::markRemove(Entity * entity)
{
    m_isAnimationing=true;
    //Entity * entity;
    //entity=entity1;
    int tag=entity->getTag();
    //	bool istrue=entity->getIsInfty();
    //entity->retain();
    //	removeList.push_back(entity);
    //	if(entity){
    //	if(!entity->getIsNeedRemove()){
    entity->setIsNeedRemove(true);
    
    global->score++;
    //}
    //	}
    switch(global->goalindex)
    {
        case 0:
            for(int i=0;i<global->needpatriesnum;i++)
            {
                if(tag==global->needpatriesindex[i])
                {
                    global->needpatriesindexnum[i]--;
                }
            }
            break;
        default:
            break;
            
    }
    if(entity->getNowState()==Entity::rowcrush)
    {
        for(int i=0;i<MAX_WIDTH;i++)
        {
            if(entitylist[entity->getRow()][i]&&!entitylist[entity->getRow()][i]->getIsInfty()&&
               !entitylist[entity->getRow()][i]->getIsNeedRemove())
            {
                if(i!=entity->getCol()){
                    markRemove(entitylist[entity->getRow()][i]);
                }
            }
        }
    }else if(entity->getNowState()==Entity::colcrush)
    {
        for(int i=0;i<MAX_HEIGHT;i++)
        {
            if(entitylist[i][entity->getCol()]&&!entitylist[i][entity->getCol()]->getIsInfty()&&
               !entitylist[i][entity->getCol()]->getIsNeedRemove())
            {
                if(i!=entity->getRow()){
                    markRemove(entitylist[i][entity->getCol()]);
                }
            }
        }
        
        
        
    }else if(entity->getNowState()==Entity::boss)
    {
        int row=entity->getRow();
        int col=entity->getCol();
        for(int i=(row-2>0?row-2:0);i<=(row+2<(MAX_HEIGHT-1)?row+2:(MAX_HEIGHT-1));i++)
        {
            for(int j=(col-(2-abs(i-row))>0?col-(2-abs(i-row)):0);
                j<=(col+(2-abs(i-row))<(MAX_WIDTH-1)?col+(2-abs(i-row)):(MAX_WIDTH-1));j++)
            {
                
                if(entitylist[i][j]&&!entitylist[i][j]->getIsInfty()&&(i!=entity->getRow()||j!=entity->getCol())
                   &&
                   !entitylist[entity->getRow()][i]->getIsNeedRemove())
                {
                    markRemove(entitylist[i][j]);
                    //	CCLOG("i:%d,j:%d",i,j);
                }
            }
        }
    }
    //	delete entity;
    
}
void GameScene ::fillPosition()
{
    int *colEmptyInfo=new int[MAX_WIDTH];
    for(int col =0;col<MAX_WIDTH;col++)
    {
        int removedSushiOfCol = 0;//º«¬º“ª¡–÷–ø’»±µƒæ´¡È ˝
        for(int row = 0;row<MAX_HEIGHT ; row++)
        {
            
            if(NULL==entitylist[row][col])
            {
                removedSushiOfCol++;
                //	removedlist.push_back(Vec2(col,row));
            }else if(entitylist[row][col]->getIsInfty()){
                continue;
            }
            else{
                if(removedSushiOfCol>0)
                {
                    int nullentity=0;
                    int endrow=row-removedSushiOfCol;
                    
                    
                    Point startPoint=entitylist[row][col]->getPosition();
                    for(int i=0;i<row;i++)
                    {
                        if(!entitylist[i][col])
                        {
                            endrow=i;
                            break;
                        }
                    }
                    Point endPoint=Vec2(tileCoordForPosition(Vec2(col,endrow)));
                    //	CCLOG("start x:%f,end x:%f",startPoint.x,endPoint.x);
                    float speed=removedSushiOfCol/5.0;
                    
                    entitylist[row][col]->stopAllActions();
                    entitylist[row][col]->runAction(MoveTo::create(speed,endPoint));
                    entitylist[row][col]->setRow(endrow);
                    entitylist[endrow][col]=entitylist[row][ col];
                    entitylist[row][col]=NULL;
                }
            }
        }
        colEmptyInfo[col]=removedSushiOfCol;
    }
    
    for(int i=0;i<MAX_HEIGHT;i++)
    {
        for(int j=0;j<MAX_WIDTH;j++)
        {
            if(NULL==entitylist[i][j])
            {
                removedlist.push_back(Vec2(i,j));
            }
        }
    }
    for(int i=0;i<removedlist.size();i++)
    {
        CreateAndDrop(removedlist[i].x,removedlist[i].y);
    }
    removedlist.clear();
    delete []colEmptyInfo;
}
void GameScene::keyBackClicked(EventKeyboard::KeyCode keyCode, Event* event)
{
    if(keyCode==EventKeyboard::KeyCode::KEY_BACK){
        //	Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //≈–∂œµ±«∞ «∑ÒŒ™Android∆ΩÃ®
        JniMethodInfo minfo;//∂®“ÂJni∫Ø ˝–≈œ¢Ω·ππÃÂ
        //getStaticMethodInfo ¥Œ∫Ø ˝∑µªÿ“ª∏ˆbool÷µ±Ì æ «∑Ò’“µΩ¥À∫Ø ˝
        bool isHave = JniHelper::getMethodInfo(minfo,"org/cocos2dx/cpp/AppActivity","dialogCloseCallBack", "()V");
        
        if (!isHave) {
            CCLog("jni:not exist");
        }else{
            CCLog("jni:exist");
            //µ˜”√¥À∫Ø ˝
            minfo.env->CallStaticVoidMethod(minfo.classID, minfo.methodID);
        }
        CCLog("jni-java∫Ø ˝÷¥––ÕÍ±œ");
#endif
    }
}

bool GameScene::isCanSwap(Entity * entity1,Entity *entity2)
{
    if(entity1->getCol()==entity2->getCol())
    {
        if(abs(entity1->getRow()-entity2->getRow())==1)
        {
            return true;
        }
    }
    if(entity1->getRow()==entity2->getRow())
    {
        if(abs(entity1->getCol()-entity2->getCol())==1)
        {
            return true;
        }
    }
    return false;
}
void GameScene::explode(Point p)
{
    auto particleStars = ParticleSystemQuad::create("stars.plist");
    particleStars->setAutoRemoveOnFinish(true);
    particleStars->setBlendAdditive(false);
    particleStars->setPosition(p);
    particleStars->setScale(0.3);
    addChild(particleStars, 20);
    CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("audio/explode.wav");
}
void GameScene ::swap(Entity * first,Entity * sec)
{
    
    int tmprow=first->getRow();
    int tmpcol=first->getCol();
    first->setRow(sec->getRow());
    first->setCol(sec->getCol());
    sec->setRow(tmprow);
    sec->setCol(tmpcol);
    entitylist[first->getRow()][ first->getCol()]=first;
    entitylist[sec->getRow()][sec->getCol()]=sec;
    Vec2 tmp=tileCoordForPosition(Vec2(tmpcol,tmprow));
    first->stopAllActions();
    sec->stopAllActions();
    if(isNeedRemove(first,sec)){
        first->runAction(MoveTo::create(0.2,tileCoordForPosition(Vec2(first->getCol(),first->getRow()))));
        sec->runAction(MoveTo::create(0.2,tileCoordForPosition(Vec2(sec->getCol(),sec->getRow()))));
        //	CCLOG("swap");
        global->remainoperate--;
    }else
    {
        //≤ªø…œ˚≥˝ ±º¥ª÷∏¥‘≠—˘
        int tmprow=first->getRow();
        int tmpcol=first->getCol();
        first->setRow(sec->getRow());
        first->setCol(sec->getCol());
        sec->setRow(tmprow);
        sec->setCol(tmpcol);
        entitylist[first->getRow()][ first->getCol()]=first;
        entitylist[sec->getRow()][sec->getCol()]=sec;
        //Vec2 tmp=tileCoordForPosition(Vec2(tmpcol,tmprow));
        first->runAction(Sequence::create( MoveTo::create(0.2,tileCoordForPosition(Vec2(sec->getCol(),sec->getRow()))),
                                          MoveTo::create(0.1,tileCoordForPosition(Vec2(first->getCol(),first->getRow()))),NULL));
        sec->runAction(Sequence::create( MoveTo::create(0.2,tileCoordForPosition(Vec2(first->getCol(),first->getRow()))),
                                        MoveTo::create(0.1,tileCoordForPosition(Vec2(sec->getCol(),sec->getRow()))),NULL));
    }
    selectedEntities.clear();
}
bool GameScene::isNeedRemove(Entity *entity1,Entity *entity2)
{
    std::list<Entity*> rowchainlist1,colchainlist1,rowchainlist2,colchainlist2;
    getRowChain(entity1,rowchainlist1);
    
    getColChain(entity1,colchainlist1);
    getRowChain(entity2,rowchainlist2);
    getColChain(entity2,colchainlist2);
    
    int max=rowchainlist1.size()>colchainlist1.size()?rowchainlist1.size():colchainlist1.size();
    max=max>rowchainlist2.size()?max:rowchainlist2.size();
    max=max>colchainlist2.size()?max:colchainlist2.size();
    if(max>=3)
    {
        return true;
    }
    return false;
}
void GameScene::startGame(Ref *pSender,TouchEventType type)
{
    if(!isbegin){
        switch ((int)type)
        {
            case (int)(cocos2d::ui::Widget::TouchEventType::BEGAN):
                
                break;
            case (int)(cocos2d::ui::Widget::TouchEventType::ENDED):
                isbegin=true;
                startDialog->runAction(Sequence::create(FadeOut::create(1.5),
                                                        CallFunc::create(this,callfunc_selector(GameScene::dialogcloseCallBack)),NULL));
                for(int i=0;i<global->needpatriesnum;i++)
                {
                    goalnodelist[i]->runAction(MoveBy::create(1.5,Vec2(0,200)));
                }
            case (int)(cocos2d::ui::Widget::TouchEventType::CANCELED):
                
                break;
            default:
                break;
        }
    }
    
}
void GameScene::dialogcloseCallBack()
{
    startDialog->setVisible(false);
    for(int i=0;i<10;i++)
    {
        for(int j=0;j<10;j++)
        {
            int id=layer->getTileGIDAt(Vec2(i,j));
            //		CCLOG("%d",id);
            if(id!=0){
                CreateAndDrop(i,j);
            }else
            {
                entitylist[i][j]=new Entity();
                entitylist[i][j]->setIsInfty(true);
                entitylist[i][j]->setVisible(false);
                entitylist[i][j]->setRow(j);
                entitylist[i][j]->setCol(i);
                entitylist[i][j]->setPosition(tileCoordForPosition(Vec2(i,j)));
                entitylist[i][j]->setIsNeedRemove(false);
                addChild(entitylist[i][j]);
            }
        }
    }
    schedule(schedule_selector(GameScene::updategame),0.2);
    schedule(schedule_selector(GameScene::updatescore),0.1);
    schedule(schedule_selector(GameScene::checkIsAllCanRemove),5);
    auto listener2 = EventListenerTouchOneByOne::create();
    listener2->onTouchBegan = [&](Touch * touch,Event *event)
    {
        //	if(!m_isAnimationing){
        for(int i=0;i<MAX_HEIGHT;i++)
        {
            for(int j=0;j<MAX_WIDTH;j++)
            {
                
                if(entitylist[i][j]->getBoundingBox().containsPoint(touch->getLocation())&&!entitylist[i][j]->getIsInfty())
                {
                    entitylist[i][j]->runAction(JumpBy::create(0.5,Vec2(0,0),10,1));
                    selectedEntities.push(entitylist[i][j]);
                    CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("audio/touch.ogg");
                    
                    
                }
                
            }
        }
        
        if(selectedEntities.length==2)
        {
            Entity * first=selectedEntities.element[0];
            Entity * sec = selectedEntities.element[1];
            if(isCanSwap(first,sec))
            {
                //Ωªªª
                swap(first,sec);
                
            }
        }
        //	}
        return true;
    };
    switch (global->goalindex)
    {
        case 0:
            
            break;
        default:
            break;
    }
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener2, this);
    
}
void GameScene::updatescore(float dt)
{
    if(score!=global->score)
    {
        score++;
        char scorestr[20];
        sprintf(scorestr,"%d",score);
        scoreLabel->setString(scorestr);
    }
    if(remain!=global->remainoperate){
        remain--;
        char remainstr[10];
        sprintf(remainstr,"%d",remain);
        remainLabel->setString(remainstr);
    }
    bool ispass=true;
    if(global->remainoperate<=0&&!isRun)
    {
        global->remainoperate=0;
        
        ispass=false;
        falseDialog->runAction(Sequence::create( MoveTo::create(2,VisibleRect::center()),
                                                CallFunc::create(this,callfunc_selector(GameScene::CallAd)),NULL));
        scoreLabel->runAction(MoveTo::create(1,Vec2(VisibleRect::center().x+10,VisibleRect::center().y)));
        scoresprite->runAction(MoveTo::create(1,
                                              Vec2(VisibleRect::center().x-scoresprite->getContentSize().width/2
                                                   ,VisibleRect::center().y)));
        isRun=true;
        
    }
    
    for(int i=0;i<global->needpatriesnum;i++)
    {
        if(global->needpatriesindexnum[i]>0)
        {
            ispass=false;
        }
    }
    if(ispass&&!isRun)
    {
        for(int i=0;i<MAX_HEIGHT;i++)
        {
            for(int j=0;j<MAX_WIDTH;j++)
            {
                if(entitylist[i][j]->getNowState()!=Entity::normal)
                {
                    markRemove(entitylist[i][j]);
                }
            }
        }
        winDialog->runAction(Sequence::create( MoveTo::create(2,VisibleRect::center()),
                                              CallFunc::create(this,callfunc_selector(GameScene::CallAd)),NULL));
        isRun=true;
        scoreLabel->runAction(Sequence::create( MoveTo::create(1,Vec2(VisibleRect::center().x+10,VisibleRect::center().y)),
                                               CallFunc::create(this,callfunc_selector(GameScene::winCallBack)),NULL));
        scoresprite->runAction(MoveTo::create(1,Vec2(VisibleRect::center().x-scoresprite->getContentSize().width/2
                                                     ,VisibleRect::center().y)));
        //scheduleOnce(schedule_selector(GameScene::win),1);
    }
}
void GameScene::continueGame(Ref *pSender,TouchEventType type)
{
    
    Scene* scene;
    
    unscheduleAllSelectors();
    switch ((int)type)
    {
        case (int)(cocos2d::ui::Widget::TouchEventType::BEGAN):
            
            break;
        case (int)(cocos2d::ui::Widget::TouchEventType::ENDED):
            global->update();
            scene=GameScene::createScene();
            Director::getInstance()->replaceScene(TransitionFade::create(1.5,scene));
            
        case (int)(cocos2d::ui::Widget::TouchEventType::CANCELED):
            
            break;
        default:
            break;
    }
}
void GameScene::BacktoHome(Ref *pSender,TouchEventType type)
{
    
    Scene* scene;
    switch ((int)type)
    {
        case (int)(cocos2d::ui::Widget::TouchEventType::BEGAN):
            
            break;
        case (int)(cocos2d::ui::Widget::TouchEventType::ENDED):
            global->writeScore();
            global->init();
            scene=HelloWorld::createScene();
            
            Director::getInstance()->replaceScene(TransitionFade::create(1.5,scene));
            unscheduleAllSelectors();
        case (int)(cocos2d::ui::Widget::TouchEventType::CANCELED):
            
            break;
        default:
            break;
    }
}
void GameScene::winCallBack()
{
    
    
    global->score+=global->remainoperate*4;
    global->remainoperate=0;
    explode(scoreLabel->getPosition());
}
void GameScene::checkIsAllCanRemove(float dt)
{
    for(int col = 0;col<MAX_WIDTH;col++)
    {
        for(int row=0;row<MAX_HEIGHT;row++)
        {
            int id=layer->getTileGIDAt(Vec2(col,row));
            if(id!=0)
            {
                
            }
        }
    }
}
bool GameScene::isCanRemoveSuccess(Entity *entity)
{
    m_isAnimationing=true;
    int row=entity->getRow();
    int col=entity->getCol();
    
    Entity * node=new Entity();
    node->setRow(row);
    node->setCol(col);
    
    
    
    return true;
}
void GameScene::pauseDialogCallBack(Ref *pSender,TouchEventType type)
{
    switch ((int)type)
    {
        case (int)(cocos2d::ui::Widget::TouchEventType::BEGAN):
            
            break;
        case (int)(cocos2d::ui::Widget::TouchEventType::ENDED):
            pauseDialog->setVisible(true);
            //	unscheduleAllSelectors();
        case (int)(cocos2d::ui::Widget::TouchEventType::CANCELED):
            
            break;
        default:
            break;
    }
}
void GameScene:: playCallBack(Ref *pSender,TouchEventType type)
{
    switch ((int)type)
    {
        case (int)(cocos2d::ui::Widget::TouchEventType::BEGAN):
            
            break;
        case (int)(cocos2d::ui::Widget::TouchEventType::ENDED):
            pauseDialog->setVisible(false);
            //	unscheduleAllSelectors();
        case (int)(cocos2d::ui::Widget::TouchEventType::CANCELED):
            
            break;
        default:
            break;
    }
}
void GameScene:: downPartriesCallBack(Ref *pSender,TouchEventType type)
{
    int flag=0;
    switch ((int)type)
    {
        case (int)(cocos2d::ui::Widget::TouchEventType::BEGAN):
            
            break;
        case (int)(cocos2d::ui::Widget::TouchEventType::ENDED):
            for(int j=0;j<MAX_HEIGHT;j++)
            {
                for(int i=0;i<MAX_WIDTH;i++)
                {
                    if(entitylist[j][i]&&!entitylist[j][i]->getIsInfty()){
                        entitylist[j][i]->setIsNeedRemove(true);
                        flag=1;
                    }
                }
                if(flag==1)
                {
                    break;
                }
            }
            global->remainoperate--;
        case (int)(cocos2d::ui::Widget::TouchEventType::CANCELED):
            
            break;
        default:
            break;
    }
}
void GameScene:: changeMusicState(Ref* sender,CheckBoxEventType type)
{
    switch (type)
    {
        case CHECKBOX_STATE_EVENT_SELECTED:
            global->isPlayMusic=true;
            UserDefault::getInstance()->setBoolForKey("isPlay",global->isPlayMusic);
            if(!CocosDenshion::SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying())
            {
                CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic(global->musicpath,true);
            }
            CCLOG("selected");//—°÷– ±œÏ”¶
            break;
        case CHECKBOX_STATE_EVENT_UNSELECTED:
            global->isPlayMusic=false;
            CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();
            CCLOG("unselected");//Œ¥—°÷– ±œÏ”¶
            break;
        default:
            break;
    }
    UserDefault::getInstance()->setBoolForKey("isPlay",global->isPlayMusic);
}
void GameScene::CallAd()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //≈–∂œµ±«∞ «∑ÒŒ™Android∆ΩÃ®
    JniMethodInfo minfo;//∂®“ÂJni∫Ø ˝–≈œ¢Ω·ππÃÂ
    //getStaticMethodInfo ¥Œ∫Ø ˝∑µªÿ“ª∏ˆbool÷µ±Ì æ «∑Ò’“µΩ¥À∫Ø ˝
    bool isHave = JniHelper::getMethodInfo(minfo,"org/cocos2dx/cpp/AppActivity","adShowCallBack", "()V");
    if (!isHave) {
        CCLog("jni:not exist");
    }else{
        CCLog("jni:exist");
        //µ˜”√¥À∫Ø ˝
        minfo.env->CallStaticVoidMethod(minfo.classID, minfo.methodID);
    }
    CCLog("jni-java∫Ø ˝÷¥––ÕÍ±œ");
#endif
}
void GameScene:: sliderchangecallBack(Ref * sender,SliderEventType type)
{
    Slider* slider;
    int percent;
    switch (type)
    {
        case SLIDER_PERCENTCHANGED:
            slider= dynamic_cast<Slider*>(sender);
            percent=slider->getPercent();
            UserDefault::getInstance()->setIntegerForKey("volume",percent);
            global->volume=percent;
            CCLOG("percent:%d",percent);
            CocosDenshion::SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(percent/100.0);
            break;
        default:
            break;
    }
}